package service

import (
	"errors"
	"github.com/go-admin-team/go-admin-core/sdk/service"
	"gorm.io/gorm"
	"tuowei.com/app/api/models"
	"tuowei.com/app/api/service/dto"
	"tuowei.com/common/actions"
	cDto "tuowei.com/common/dto"
)

type SysShoppingCart struct {
	service.Service
}

// GetPage 获取SysAddress列表
func (e *SysShoppingCart) GetPage(c *dto.SysShoppingCartGetPageReq, p *actions.DataPermission, list *[]models.SysShoppingCart, count *int64) error {
	var err error
	var data models.SysShoppingCart

	err = e.Orm.Debug().
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			actions.Permission(data.TableName(), p),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
		).Table(data.TableName()).
		Find(list).Limit(-1).Offset(-1).Count(count).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return err
	}
	return nil
}

func (e *SysShoppingCart) Get(d *dto.SysShoppingCartGetReq, p *actions.DataPermission, model *models.SysShoppingCart) error {
	var data models.SysShoppingCart

	err := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).
		First(model, d.GetId()).Error

	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		e.Log.Errorf("db error: %s", err)
		return err
	}

	return nil
}

// Insert 创建SysAddress对象
func (e *SysShoppingCart) Insert(c *dto.SysShoppingCartInsertReq, name, subject, introduction, courseType, cover string, price float64) error {
	var err error
	var data models.SysShoppingCart

	c.Generate(&data, name, subject, introduction, courseType, cover, price)

	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("db error: %s", err)
		return err
	}

	return nil
}

func (e *SysShoppingCart) Update(c *dto.SysShoppingCartUpdateReq) error {
	var err error
	var model = models.SysShoppingCart{}
	e.Orm.First(&model, c.GetId())
	c.Generate(&model)
	db := e.Orm.Save(&model)
	err = db.Error
	if err != nil {
		e.Log.Errorf("Service Update SysShoppingCartUpdateReq error:%s", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")

	}
	return nil
}

// Remove 删除SysAddress
func (e *SysShoppingCart) Remove(d *dto.SysShoppingCartDeleteReq) error {
	var err error
	var data models.SysShoppingCart

	db := e.Orm.Model(&data).Delete(&data, d.GetId())
	if db.Error != nil {
		err = db.Error
		e.Log.Errorf("Delete error: %s", err)
		return err
	}
	if db.RowsAffected == 0 {
		err = errors.New("无权删除该数据")
		return err
	}
	return nil
}
